<?php

/**
 * @package EDO
 * @subpackage Collections
 *
 */
class EDO_collection_Paged extends Lead_EDO_Collection_Abstract 
{

	protected $_numberOfPages  = 0;
	protected $_currentPage = 1;
	
	protected $_pageSize = 10;
	
	protected $_totalLength = 0;
	
	protected $_allItems = array();
	
	
	public function __construct(EDOHandler $edo)
	{
		$this->attach($this, 'onAddItem', 'setPagesItems');
		$this->attach($this, 'onSetPage', 'setPagesItems');
		$this->attach($this, 'onSetPageSize', 'setPagesItems');
		parent::__construct($edo);
	}
	
	
	public function addItem($res)
	{
		array_push($this->_allItems, $res);
		$this->_totalLength++;
						
		$this->triggerEvent('onAddItem');
				
						
	}
	
	public function setPage($page)
	{
		$this->_currentPage = $page;
		$this->triggerEvent('onSetPage');
	}

	public function getNumberOfPages()
	{
		return $this->_numberOfPages;
	}

	public function getPage()
	{
		return $this->_currentPage;
	}
	
	public function setPageSize($pageSize)
	{
		$this->_pageSize = $pageSize;
		$this->triggerEvent('onSetPageSize');
	}
	
	
	protected function setPagesItems()
	{
		if(sizeof($this->_allItems) < $this->_pageSize)
		{
			$this->_length = $this->_totalLength;
			$this->_items = $this->_allItems;
		}
		else 
		{
		
			$start = ($this->_currentPage - 1) * $this->_pageSize;
			$end = $start + $this->_pageSize;
				
			
			$this->_items = array_slice($this->_allItems, $start, $this->_pageSize);
			
			$this->_length = sizeof($this->_items);
		
		}

		$this->_numberOfPages = (ceil($this->_totalLength / $this->_pageSize));	
		
	}
	
	public function length()
	{
		return $this->_totalLength;
	}
	
	
	public function getKeys()
	{
		return array_values($this->_allItems);
	}
	
	public function getSerializedKeys($serializer = ';')
	{
		return implode($serializer, $this->getKeys());
	}


}
